package com.example.demo.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.common.response.ResponseData;
import com.example.demo.entity.param.EsQueryParam;
import com.example.demo.entity.po.Student;
import com.example.demo.util.DateUtil;
import com.example.demo.util.EsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.example.demo.util.common.ResponseDataUtil.responseData;
import java.util.List;

/**
 * (Test2)控制层
 *
 * @author wbx
 * @since 2021-05-14 11:08:06
 */
@RestController
@Api(value = "", tags = "  by wbx")
@RequestMapping("/student")
@Validated
public class StudentController {

    final static String indexName = "student";

    /**
     *  添加ES数据
     */
    @ApiOperation("添加ES数据")
    @PostMapping("/addStudent")
    public ResponseData<Boolean> addStudent(@RequestBody @Validated Student student) {
        student.setCreateTime(DateUtil.getCurrentDateTimeStr());
        boolean b = EsUtil.addDoc(indexName, JSONObject.fromObject(student));
        return responseData(b);
    }

    /**
     *  删除ES数据
     */
    @ApiOperation("删除ES数据")
    @PostMapping("/deleteStudent")
    public ResponseData<Boolean> deleteStudent(@RequestBody @Validated Student student) {
        boolean b = EsUtil.deleteById(indexName, String.valueOf(student.getId()));
        return responseData(b);
    }

    /**
     *  修改ES数据
     */
    @ApiOperation("修改ES数据")
    @PostMapping("/updateStudent")
    public ResponseData<Boolean> updateStudent(@RequestBody @Validated Student student) {
        boolean b = EsUtil.updateDoc(indexName, JSONObject.fromObject(student));
        return responseData(b);
    }

    /**
     *  根据ID查询ES数据
     */
    @ApiOperation("根据ID查询ES数据")
    @PostMapping("/queryStudentByID")
    public ResponseData<JSONObject> queryStudentByID(@RequestBody @Validated Student student) {
        JSONObject docByID = EsUtil.getDocByID(indexName, String.valueOf(student.getId()));
        return responseData(docByID);
    }

    /**
     *  查询ES分页并设置高亮
     */
    @PostMapping("/searchHighLightPageByKeywords")
    @ApiOperation("查询ES数据高亮")
    public ResponseData<List<JSONObject>> searchHighLightPageByKeywords(@RequestBody @Validated EsQueryParam queryParam) {
        IPage<JSONObject> page = EsUtil.searchHighLightPageByKeywords(queryParam.getIndexName(), JSONObject.fromObject(queryParam),JSONObject.class);
        return responseData(page);
    }

}
